#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
#include<tuple>
using namespace std;



class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int len = nums.size();
        vector<vector<int>> ans;
        set<tuple<int, int, int>> judge_same;
        for (int i = 0; i < len - 2; i++) {
            if (nums[i] + nums[i + 1] + nums[i + 2] > 0) return ans;
            if (nums[i] + nums[len - 2] + nums[len - 1] < 0) continue;
            for (int j = i + 1; j < len - 1; j++) {
                if (nums[i] + nums[j] + nums[j + 1] > 0) break;
                else if (nums[i] + nums[j] + nums[len - 1] < 0) continue;
                for (int z = j + 1; z < len; z++) {
                    if (nums[i] + nums[j] + nums[z] == 0 && !judge_same.count({ nums[i], nums[j], nums[z] })) {
                        judge_same.insert({ nums[i], nums[j], nums[z] });
                        ans.push_back({ nums[i], nums[j], nums[z] });
                    }
                }
            }
        }
        return ans;
    }
};



class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int len = nums.size();
        vector<vector<int>> ans;
        for (int i = 0; i < len - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int left = i + 1;
            int right = len - 1;
            while (left < right) {
                int tmp = nums[i] + nums[left] + nums[right];
                if (tmp > 0) {
                    right--;
                }
                else if (tmp < 0) {
                    left++;
                }
                else {
                    ans.push_back({ nums[i], nums[left], nums[right] });
                    while (left < right && nums[left] == nums[left + 1])
                        left++;
                    while (left < right && nums[right] == nums[right - 1])
                        right--;
                    right--;
                    left++;
                }
            }
        }
        return ans;
    }
};